import { defineStore } from "pinia";
import { ref, computed } from "vue";
import dayjs from "dayjs";

// 模块外部的全局定时器
let intervalStarted = false;

export const useOrderStore = defineStore("order", () => {


    const orderDetailList = ref([]);
    const orderId = ref("");
    const totalAmount = ref(0);
    const createTime = ref(0); // 创建时间戳

    const time = ref(0); // 剩余时间（秒）
    const endTime = ref(0); // 倒计时结束时间戳

    // 格式化时间
    const formatTime = computed(() => {
        return dayjs.unix(time.value).format("mm分ss秒");
    });

    // 设置新倒计时
    const startCountdown = (durationInSeconds) => {
        const now = Math.floor(Date.now() / 1000);
        endTime.value = now + durationInSeconds;
        updateCountdown();
    };

    // 页面恢复时调用
    const resumeCountdown = () => {
        updateCountdown();
    };

    // 每秒更新倒计时
    const updateCountdown = () => {
        const now = Math.floor(Date.now() / 1000);
        if (endTime.value > now) {
            time.value = endTime.value - now;
        } else {
            if (time.value > 0) {
                // 只清一次
                clearOrder();
            }
            time.value = 0;
        }
    };

    // 清除所有数据
    const clearOrder = () => {
        orderDetailList.value = [];
        orderId.value = "";
        totalAmount.value = 0;
        time.value = 0;
        endTime.value = 0;

    };

    // 初始化时启动全局倒计时定时器
    if (!intervalStarted) {
        setInterval(() => {
            updateCountdown();
        }, 1000);
        intervalStarted = true;
    }

    return {
        orderDetailList,
        orderId,
        totalAmount,
        createTime,
        time,
        endTime,
        formatTime,
        startCountdown,
        resumeCountdown,
        clearOrder
    };
}, {
    persist: true
});
